package com.gx.auth.service.impl;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.gx.auth.entity.Function;
import com.gx.auth.service.LoginInterfaceService;
import com.gx.security.CSRFTokenManager;

public class LoginInterfaceImplService implements LoginInterfaceService {
	private static Logger log = Logger.getLogger(LoginInterfaceImplService.class);
	private static final String CACHE_CONTROL = "Cache-Control";
	private static final String NO_CACHE = "no-cache";
	private static final String ENCODING = "utf-8";
	private String CHECK_CODE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	private String STRCODE = "strCode";

	@Override
	public void getVerificationCode(HttpServletRequest request, HttpServletResponse response) {

		try {
			response.setDateHeader("Expires", 0);
			response.addHeader(CACHE_CONTROL, NO_CACHE);// 浏览器和缓存服务器都不应该缓存页面信息
			response.addHeader(CACHE_CONTROL, NO_CACHE);// 请求和响应的信息都不应该被存储在对方的磁盘系统中；
			response.setCharacterEncoding(ENCODING);
			request.setCharacterEncoding(ENCODING);
			BufferedImage bi = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
			Graphics g = bi.getGraphics();
			Color c = new Color(200, 150, 255);
			g.setColor(c);
			g.fillRect(0, 0, 68, 22);
			StringBuilder sb = new StringBuilder();
			char[] ch = CHECK_CODE.toCharArray();
			Random r = new Random();
			int len = ch.length;
			for (int i = 0; i < 4; i++) {
				int index = r.nextInt(len);
				g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
				g.drawString(ch[index] + "", (i * 15) + 3, 18);
				sb.append(ch[index]);
			}
			request.getSession().setAttribute(STRCODE, sb.toString());
			ImageIO.write(bi, "JPG", response.getOutputStream());
			response.getOutputStream().close();
		} catch (IOException e) {
			log.info(e.getCause(),e);
		}

	}

	@Override
	public void loginCheck(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		
		try {
			response.addHeader(CACHE_CONTROL, NO_CACHE);// 浏览器和缓存服务器都不应该缓存页面信息
			response.addHeader(CACHE_CONTROL, NO_CACHE);// 请求和响应的信息都不应该被存储在对方的磁盘系统中；
			response.setCharacterEncoding(ENCODING);
			request.setCharacterEncoding(ENCODING);
			// 获取传递的值
			String authCode = request.getParameter("verify");
			String verifyCode = (String) request.getSession().getAttribute(STRCODE);
			String uname = request.getParameter("uname");
			String password = request.getParameter("pwd");
			log.info(uname);
			UserInterfaceImplService userInfaImplSer = new UserInterfaceImplService();
			Boolean isUpwd = userInfaImplSer.checkPwd(uname, password);
			List<Function> lisFunc = userInfaImplSer.getUserFunction(uname);

			if (isUpwd && verifyCode.equals(authCode)) {
				log.info(uname + "登录成功");
				session.setAttribute("username", uname);
				session.setAttribute("upermission", lisFunc);
				session.setAttribute("csrf", CSRFTokenManager.getTokenForSession(session));
				// 验证码无效化处理
				//session.removeAttribute(strCode);
				log.info(CSRFTokenManager.getTokenForSession(session).toString());
				request.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request, response);
			} else {
				log.info(uname + "登录失败");
				request.setAttribute("loginerro", "账户/密码/验证码错误，请重新验证登录");
				response.sendRedirect(request.getContextPath() + "/login/login.jsp");
			}
		} catch (IOException | ServletException e) {
			log.info(e.getCause(),e);
		}
	}

}
